import { Component, OnInit, EventEmitter, Output } from '@angular/core'
import { DValidateRules, FormLayout, LoadingService } from 'ng-devui'
import { ManageService } from 'src/app/@core/manage.service'
import { number } from 'echarts'
import { Router } from '@angular/router'

@Component({
  selector: 'app-mint',
  templateUrl: './mint.component.html',
  styleUrls: ['./mint.component.scss']
})
export class MintComponent implements OnInit {
  @Output() apply = new EventEmitter()
  layoutDirection: FormLayout = FormLayout.Vertical
  userId = parseInt(localStorage.getItem('userId'))
  msgs: Array<Object> = []
  options2 = [{}]
  currentOption4 = { value: number }

  options3 = [
    {
      name: '动漫',
      value: 1
    },
    {
      name: '艺术',
      value: 2
    },
    {
      name: '文物',
      value: 3
    }
  ]

  public img = null

  formRules: { [key: string]: DValidateRules } = {
    rule: {
      message: '校验失败，请检查铸造信息',
      messageShowType: "none"
    },
    fileUrlRules: {
      validators: [{ required: true }]
    },
    nameRules: {
      validators: [
        { minlength: 1 },
        { maxlength: 64 },
        { required: true }
      ]
    },
    collectionIndexRules: {
      validators: [{ required: true }]
    },
    categoryRules: {
      validators: [{ required: true }]
    },
    descriptionRules: {
      validators: [{ required: true }]
    },
    mintAmountRules: {
      validators: [{ required: true }]
    },
    fileUrl: {
      validators: [{ required: true }]
    }
  }

  constructor(
    public manageService: ManageService,
    private loadingService: LoadingService,
    private router: Router,
  ) { }

  private showLoading: any
  form: Array<any> = []

  ngOnInit(): void {
    this.form.splice(0, this.form.length);
    this.currentOption4 = { value: number };
    var formData1 = {}
    formData1 = {
      img: '',
      name: '',
      collectionIndex: this.currentOption4,
      category: { value: '' },
      mintAmount: '',
      description: '',
      fileUrl: '',
      author: ''
    }
    this.form.push(formData1)
    this.getInVisible()
  }

  collectionDisabled = false

  getInVisible() {
    let arr = []
    this.manageService.collectionNamesInvisible().subscribe((res) => {
      let list = res.data.collection;
      if (list === null) {
        this.showToast('error', '', '暂无有效藏品集合，请先新建藏品集合！')
        this.collectionDisabled = true
      } else {
        this.collectionDisabled = false
        list.forEach((item) => {
          arr.push({
            name: item.collectionName,
            value: item.collectionIndex
          })
        })
        this.options2 = arr
      }
    })
  }

  uploadFile(i) {
    document.getElementById('file' + i.toString()).click()
  }

  fileChange(e, index, fd) {
    var file = e.target.files[0]
    var formData = new FormData()
    if (!file.type.includes('image')) {
      this.showToast('error', '', '请选择图片！')
      return false
    }
    if (file.size > 10 * 1024 * 1024) {
      this.showToast('error', '', '不能超过10M！')
      return false
    }
    formData.append('file', file)
    if (e.target.files[0]) {
      var reader = new FileReader()
      if (file.type.indexOf('image') != -1) {
        reader.readAsDataURL(file)
        reader.onload = () => {
          fd.img = reader.result
        }
      }
      this.manageService.upLoadImg(formData).subscribe((res) => {
        fd.fileUrl = res.data?.obsKey
      })
    }
  }

  submitForm({ valid }) {
    if (valid) {
      var mintData: Array<any> = []
      this.form.forEach((item) => {
        var newParam = {}
        newParam['collectionIndex'] = this.currentOption4.value
        newParam['fileUrl'] = item.fileUrl
        newParam['name'] = item.name
        newParam['description'] = item.description
        newParam['category'] = item.category.value
        newParam['mintAmount'] = item.mintAmount
        newParam['issuer'] = item.author
        mintData.push(newParam)
      })
      this.showLoading = this.loadingService.open({
        message: '铸造中，请稍等……'
      })
      this.manageService.chainMint(this.userId, mintData).subscribe((res) => {
        if (res.code == 0) {
          this.showLoading.loadingInstance.close()
          this.showToast('success', '', '铸造成功！')
          this.form.splice(0, this.form.length);
          this.currentOption4 = { value: number };
          this.add()
          this.apply.emit()
        } else {
          this.showLoading.loadingInstance.close()
          this.showToast('error', '', res.msg)
        }
      })
    } else {
      this.showToast('error', '', '请检查表单!')
    }
  }
  
  showToast(type: any, title: string, msg: string) {
    this.msgs = [{ severity: type, summary: title, detail: msg }]
  }

  Mintvalidator(fd) {
    return parseInt(fd.mintAmount) > 5000
  }

  add() {
    var formData1 = {}
    formData1 = {
      img: '',
      name: '',
      collectionIndex: this.currentOption4,
      category: { value: '' },
      mintAmount: '',
      description: '',
      fileUrl: '',
      author: ''
    }
    this.form.push(formData1)
  }

  cancel(i) {
    this.form.splice(i, 1)
  }

  ngOnDestroy(): void {
    this.form.splice(0, this.form.length);
  }

  get(str, i) {
    return str + i.toString()
  }
}

